package cn.study.server.handler;

import cn.study.message.ChatRequestMessage;
import cn.study.message.ChatResponseMessage;
import cn.study.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author Zsz
 * @Date 2022/4/4 21:13
 * @Version 1.0
 **/
@Slf4j
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();
        Channel channel = SessionFactory.getSession().getChannel(to);
        if (channel != null) {
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
        } else {
            channelHandlerContext.writeAndFlush(new ChatResponseMessage(false, "发送失败，原因：对方不存在或对方不在线！"));
        }
    }
}
